package com.linkoog.devtools.datafaker.generator;

import com.linkoog.devtools.datafaker.Generator;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class AddressGenerator implements Generator {

    @Override
    public String generate() {
        Pair randomProvince = getRandomSubObject(data);
        Pair randomCity = getRandomSubObject(randomProvince.value);

        final Map<String, Object> map = randomCity.value;
        ArrayList<String> list = new ArrayList(map.keySet());
        String areaName = list.get(random.nextInt(list.size()));
        List<String> streets = (List<String>)map.get(areaName);
        String streetName = streets.get(random.nextInt(streets.size()));

        return randomProvince.name + randomCity.name + areaName + streetName;
    }

    private static Pair getRandomSubObject(Map<String, Object> map){
        ArrayList<String> list = new ArrayList(map.keySet());
        String name = list.get(random.nextInt(list.size()));
        return new Pair(name, (Map<String, Object>)map.get(name));
    }

    private static Yaml yaml = new Yaml();
    private static Map<String, Object> data;
    private static Random random = new Random();

    static {
        ClassLoader loader = AddressGenerator.class.getClassLoader();
        try (InputStream input = loader.getResourceAsStream("address.yml")) {
            data = yaml.load(input);
        } catch (IOException ignored) {
            data = new HashMap<>();
        }
    }

    private static class Pair{
        String name;
        Map<String, Object> value;

        public Pair(String name, Map<String, Object> value){
            this.name = name;
            this.value = value;
        }
    }

}
